package com.kz.framework.proxy;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.kz.framework.annotation.aop.MyAfter;
import com.kz.framework.annotation.aop.MyBefore;

import lombok.Data;

/**
 * @author zhgp
 * @version 1.0
 * @description: 代理方法的信息
 * @date 2021/7/2 22:45
 */
@Data
public class ProxyChain {
    private static final Logger LOGGER = LoggerFactory.getLogger(ProxyChain.class);
    /**
     * 切点的方法
     */
    private Method method;
    /**
     * 切点的对象
     */
    private Object target;
    /**
     * 切点的参数
     */
    private Object[] args;

    /**
     * 上下文
     */
    private ProceedingJoinPoint point;

    public ProxyChain(Method method, Object target, Object... args) {
        this.method = method;
        this.target = target;
        this.args = args;
    }

    /**
     * @description: 执行目标对象的方法
     * @param
     * @return: java.lang.Object
     * @author zhgp
     * @date: 2021/7/2 22:47
     */
    public Object invoker() throws InvocationTargetException, IllegalAccessException {
        if (point != null) {
            MyBefore before = method.getAnnotation(MyBefore.class);
            if (before != null) {
                invokeProxy();
                return point.proceed(point.getArgs());
            }
            MyAfter after = method.getAnnotation(MyAfter.class);
            if (after != null) {
                Object o = point.proceed(point.getArgs());
                invokeProxy();
                return o;
            }
        }
        return invokeProxy();
    }

    /**
     * @description: 执行增强方法 也就是Aspect注解类的方法
     * @author zhgp
     * @date 2023/7/22 13:32
     * @version 1.0
     */
    private Object invokeProxy() throws InvocationTargetException, IllegalAccessException {
        LOGGER.info("执行增强方法：" + method.getName());
        method.setAccessible(true);
        return method.invoke(target, args);
    }
}
